#!/usr/bin/python
# -*- coding: utf-8 -*-  
"""
@Project : hello 
@file : job_monitor.py
@Author : shenj
@time : 2025/5/28 15:20
@func :
"""
# job_monitor.py

import logging
import time
from typing import List, Dict, Any, Optional

from com.cn.for_cdc.common.log_helper import configure_logging
from mysql_demo import MySQLHelper

configure_logging(log_format="[%(asctime)s] %(message)s")


class JobMonitor:
    def __init__(self, poll_interval: int = 60, timeout_seconds: int = 3600):
        self.poll_interval = poll_interval  # 轮询间隔（秒）
        self.timeout_seconds = timeout_seconds  # 最大等待时间（秒）

    def check_rerun_status(self, db: MySQLHelper, bu: str, job_ids: List[int]) -> None:
        """批量检查任务的重跑状态"""
        logging.info(f"开始检查重跑状态: BU={bu}, job_ids={job_ids}")
        for job_id in job_ids:
            self.wait_for_job_completion(db, bu, job_id)

    def wait_for_job_completion(self, db: MySQLHelper, bu: str, job_id: int) -> bool:
        """等待单个任务完成，并返回执行结果"""
        start_time = time.time()
        logging.info(f"开始轮询任务状态: BU={bu}, job_id={job_id}")

        while True:
            status = self._get_latest_job_status(db, bu, job_id)
            if status == 'S':
                logging.info(f"任务执行成功: BU={bu}, job_id={job_id}")
                return True
            elif status == 'F':
                logging.error(f"任务执行失败: BU={bu}, job_id={job_id}")
                return False

            elapsed = time.time() - start_time
            if elapsed > self.timeout_seconds:
                logging.warning(f"任务等待超时: BU={bu}, job_id={job_id}, 已超过{self.timeout_seconds}秒")
                return False

            logging.info(f"任务仍在运行，等待下一轮检查: BU={bu}, job_id={job_id}")
            time.sleep(self.poll_interval)

    def _get_latest_job_status(self, db: MySQLHelper, bu: str, job_id: int) -> Optional[str]:
        """获取任务最新日志中的状态"""
        sql = f"""
            SELECT STATUS 
            FROM asw_etl_{bu}_job.XX_JOB_LOG 
            WHERE job_id = {job_id}
              AND created_time >= DATE_FORMAT(NOW(), '%Y-%m-%d 00:00:00') 
            ORDER BY created_time DESC 
            LIMIT 1;
        """
        result = db.query(sql)
        if result and isinstance(result, list) and len(result) > 0:
            return result[0].get("STATUS")
        return None
